package control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dataaccess.CarDB;
import dataaccess.UsersDB;
import domain.CarList;
import domain.User;

public class CarListAction extends HttpServlet {
	boolean followForward = true;// flag used to make sure the page only
									// forwards the request once
	CarDB cdb = new CarDB();// connects to the car database
	UsersDB udb = new UsersDB();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user;
		user = (User) session.getAttribute("userinfo");

		if (user == null || !udb.checkLogin(user)) {

			if (followForward) {
				System.out
						.println("user info not found or incorrect -- redirecting to login page ");

				getServletConfig().getServletContext()
						.getRequestDispatcher("/LoginPage.jsp")
						.forward(request, response);
				followForward = false;
			}

		} else {// if login info is correct we proceed to the car list page
			if (followForward) {
				CarList carlist = cdb.getCarList();
				session.setAttribute("carlist", carlist);
				System.out
						.println("user info correct! retrieved car list and  redirecting to CarList page ");

				getServletConfig().getServletContext()
						.getRequestDispatcher("/CarListPage.jsp")
						.forward(request, response);
				followForward = false;
			}

		}
		followForward = true;
	}
}
